package cn.jiaqiang.chatgpt.data.trigger.http.interceptors;

import cn.jiaqiang.chatgpt.data.domain.auth.service.AuthService;
import cn.jiaqiang.chatgpt.data.types.holder.RequestHolder;
import cn.jiaqiang.chatgpt.data.types.holder.ResponseHolder;
import cn.jiaqiang.chatgpt.data.types.holder.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private AuthService authService;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
            return true;
        }

        // 判断是否拦截(ThreadLocal是否用用户信息)
        String token = request.getHeader("Authorization");
        String userId = authService.userId(token);
        if (userId == null) {
//            response.setStatus(401);
            return true;
        }
        UserHolder.saveUser(Long.parseLong(userId));
        RequestHolder.saveRequest(request);
        ResponseHolder.saveResponse(response);
        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) {
        UserHolder.removeUserID();
        RequestHolder.removeRequest();
        ResponseHolder.removeResponse();
    }
}
